﻿using System.Collections;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System;
using U8Login;
using YonYou.U8.IN.Framework;

namespace Yonyou.U8.QuickImport
{
    public class DataImport
    {
        private const double COEEFF = 0.5;

        private FormProgress fpBar;

        private int NowDocNum;

        private string m_proctype;

        private IDataImport datatoxml;

        private EaiImport eaiimport;

        private Context _Context;

        public DataImport(Context context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            _Context = context;
            fpBar = new FormProgress();
            eaiimport = new EaiImport();
        }

        private void InitIData(string filetype)
        {
            if (string.Compare(filetype, ".txt", true) == 0 || string.Compare(filetype, ".csv", true) == 0)
            {
                datatoxml = new TxtToXml(_Context);
            }
            else
            {
                datatoxml = new ExcelToXml(_Context);
            }
            datatoxml.InitSetup += InitialProgressBar;
            datatoxml.ValueSet += SetProgressBar;
        }

        public bool transimport(string xml, clsLogin u8login, ref string querytoken, Form mainwnd)
        {
            fpBar.Owner = mainwnd;
            string token = (querytoken = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond);
            string proctype;
            string logpath;
            string altertype;
            XmlNodeList nodelist;
            if (!parseXml(xml, out proctype, out logpath, out altertype, out nodelist))
            {
                return false;
            }

            m_proctype = proctype;
            try
            {
                bool result = true;
                bool flag = false;
                int count = 0;
                int scount = 0;
                NowDocNum = 0;
                fpBar.Show(ViewAdvisor.Instance.MainForm);
                Application.DoEvents();
                foreach (XmlNode item in nodelist)
                {
                    Application.DoEvents();
                    fpBar.Init(nodelist.Count);
                    NowDocNum++;
                    string text = item.Attributes["id"].InnerText;
                    string innerText = item.Attributes["name"].InnerText;
                    string billAuthId = CommonUtil.GetBillAuthId(innerText);
                    string innerText2 = item.Attributes["filename"].InnerText;
                    string extension = Path.GetExtension(innerText2);
                    InitIData(extension);
                    if (!CommonUtil.CheckAuthValid(_Context.Login, billAuthId))
                    {
                        writelog(new string[2, 1]
                        {
                        { "导入失败原因" },
                        { "当前用户无导入权限" }
                        }, text, logpath, u8login, innerText2, innerText, 0, 0, token, proctype, null);
                        if (!MessageHelper.ShowTipMessage(string.Format("当前用户无{0}的导入权限，是否继续导入其他单据？", innerText), "提示信息"))
                        {
                            fpBar.ClosePro();
                            return false;
                        }
                        continue;
                    }
                    string path = Path.Combine(_Context.QICurrentModelPath, innerText2);
                    string filename = Path.Combine(Context.U8Path, "ExcelModel\\ChildArch.xml");
                    string msg = string.Empty;
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(filename);
                    if (!CommonUtil.CheckExSelfDefineItem(text, path, xmlDocument.InnerXml, _Context.Login, ref msg))
                    {
                        string empty = string.Empty;
                        empty = ((!msg.Contains("扩展自定义项")) ? msg : string.Format("当前帐套不存在如下扩展自定义项:{0}.", msg));
                        MessageHelper.ShowMessage("扩展自定义项校验失败", empty);
                        fpBar.ClosePro();
                        writelog(new string[2, 1]
                        {
                        { "导入失败原因" },
                        { empty }
                        }, text, logpath, u8login, innerText2, innerText, 0, 0, token, proctype, null);
                        return false;
                    }
                    if (text == "unit")
                    {
                        text = "unitgroup";
                    }
                    for (int i = 0; i < 2; i++)
                    {
                        string[] array = datatoxml.transform(text, innerText2, proctype);
                        if (datatoxml.ArchIsEmpty)
                        {
                            fpBar.ClosePro();
                            writelog(new string[2, 1]
                            {
                            { "导入失败原因" },
                            { "没有数据" }
                            }, text, logpath, u8login, innerText2, innerText, 0, 0, token, proctype, null);
                            break;
                        }
                        if (!XmlIsValid(array))
                        {
                            fpBar.ClosePro();
                            return false;
                        }
                        XmlDocument xmlDocument2 = new XmlDocument();
                        xmlDocument2.LoadXml(array[0]);
                        XmlTextWriter xmlTextWriter = new XmlTextWriter(Context.QIPath + "\\data.xml", null);
                        xmlTextWriter.Formatting = Formatting.Indented;
                        xmlDocument2.Save(xmlTextWriter);
                        xmlTextWriter.Close();
                        string[] array2 = ((!(proctype != "4")) ? array : ParseXmlOnebyOne(text, array));
                        int num = array2.Length;
                        string[] array3 = new string[num];
                        if (array2 == null || array2.Length == 0)
                        {
                            fpBar.ClosePro();
                            writelog(new string[2, 1]
                            {
                            { "导入失败原因" },
                            { "转换后的单据数据条目为空，请检查标记为蓝色的关键字段的值是否缺失。" }
                            }, text, logpath, u8login, innerText2, innerText, 0, 0, token, proctype, null);
                            return false;
                        }
                        for (int j = 0; j < array2.Length; j++)
                        {
                            if (array2[j] == null || array2[j].Trim() == "")
                            {
                                fpBar.ClosePro();
                                return false;
                            }
                            XmlDocument xmlDocument3 = new XmlDocument();
                            try
                            {
                                xmlDocument3.LoadXml(array2[j]);
                            }
                            catch (XmlException ex)
                            {
                                fpBar.ClosePro();
                                MessageBox.Show("数据转换后的xml格式错误：" + ex.Message);
                                return false;
                            }
                            array3[j] = eaiimport.ImportToDB(array2[j], u8login);
                            SetImportProgressBar(array3[j]);
                            StreamWriter streamWriter = new StreamWriter(Context.QIPath + "\\return.xml");
                            streamWriter.WriteLine(array3[j]);
                            streamWriter.Close();
                        }
                        try
                        {
                            if (array3.Length > 1)
                            {
                                XmlDocument xmlDocument4 = new XmlDocument();
                                XmlDocument xmlDocument5 = new XmlDocument();
                                xmlDocument4.LoadXml(array3[0]);
                                for (int k = 1; k < array3.Length; k++)
                                {
                                    xmlDocument5.LoadXml(array3[k]);
                                    XmlNodeList xmlNodeList = xmlDocument5.SelectNodes("/ufinterface/item");
                                    for (int l = 0; l < xmlNodeList.Count; l++)
                                    {
                                        XmlElement xmlElement = xmlDocument4.CreateElement(xmlNodeList[l].Name);
                                        for (int m = 0; m < xmlNodeList[l].Attributes.Count; m++)
                                        {
                                            XmlAttribute xmlAttribute = xmlDocument4.CreateAttribute(xmlNodeList[l].Attributes[m].Name);
                                            xmlAttribute.Value = xmlNodeList[l].Attributes[m].Value;
                                            xmlElement.Attributes.Append(xmlAttribute);
                                        }
                                        xmlDocument4.DocumentElement.AppendChild(xmlElement);
                                    }
                                }
                                xmlDocument4.Save(Context.QIPath + "\\returnAll.xml");
                            }
                        }
                        catch (Exception)
                        {
                        }
                        string[,] strLog = AdjustReturnStr(array2, array3);
                        GetSucceedImportCount(array3, ref count, ref scount);
                        writelog(strLog, text, logpath, u8login, innerText2, innerText, count, scount, token, proctype, array3);
                        if (scount != count && text != "unitgroup" && text != "unitdocument")
                        {
                            result = false;
                            flag = true;
                        }
                        if (flag && altertype == "1")
                        {
                            string text2 = "";
                            switch (proctype)
                            {
                                case "1":
                                    text2 = "导入出错，是否继续";
                                    break;
                                case "2":
                                    text2 = "导入出错，是否继续";
                                    break;
                                case "3":
                                    text2 = "删除数据出错，是否继续";
                                    break;
                                case "4":
                                    text2 = "清空数据出错，是否继续";
                                    break;
                            }
                            DialogResult dialogResult = MessageBox.Show(Path.GetFileNameWithoutExtension(innerText2) + text2, innerText, MessageBoxButtons.YesNo);
                            if (dialogResult != DialogResult.Yes)
                            {
                                fpBar.ClosePro();
                                return false;
                            }
                            flag = false;
                        }
                        if (text == "unitgroup")
                        {
                            text = "unit";
                            continue;
                        }
                        if (!(text == "unitdocument"))
                        {
                            break;
                        }
                        text = "unitaccount";
                    }
                }
                fpBar.ClosePro();
                return result;
            }
            catch (Exception ex3)
            {
                fpBar.ClosePro();
                MessageHelper.ShowMessage("数据导入错误", ex3.Message);
                return false;
            }
        }

        public static bool parseXml(string xml, out string proctype, out string logpath, out string altertype, out XmlNodeList nodelist)
        {
            XmlDocument xmlDocument = new XmlDocument();
            try
            {
                xmlDocument.LoadXml(xml);
            }
            catch (XmlException)
            {
                MessageBox.Show("导入策略xml字符串格式错误");
                proctype = "";
                logpath = "";
                altertype = "";
                nodelist = null;
                return false;
            }
            XmlNode xmlNode = xmlDocument.SelectSingleNode("/data/import");
            if (xmlNode == null)
            {
                MessageBox.Show("导入策略xml字符串不含/data/import节点");
                proctype = "";
                logpath = "";
                altertype = "";
                nodelist = null;
                return false;
            }
            nodelist = xmlDocument.SelectNodes("//class/menu");
            if (nodelist == null)
            {
                MessageBox.Show("导入策略xml字符串不含/data/menu节点");
                proctype = "";
                logpath = "";
                altertype = "";
                nodelist = null;
                return false;
            }
            proctype = xmlNode.Attributes["type"].InnerText;
            logpath = xmlNode.Attributes["logfilepath"].InnerText;
            altertype = xmlNode.Attributes["alerttype"].InnerText;
            return true;
        }

        private void writelog(string[,] strLog, string id, string logpath, clsLogin u8login, string filename, string name, int count, int scount, string token, string proctype, string[] rxmlstr)
        {
            string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Context.QIPath + "\\log\\loglist.mdb;";
            OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
            oleDbConnection.Open();
            string text = id + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + Path.GetExtension(filename);
            if (!Directory.Exists(logpath))
            {
                MessageBox.Show("指定的日志路径不存在，请进入方案设置中重新指定日志路径");
                return;
            }
            string text2 = logpath + text;
            File.Copy(filename, text2, true);
            datatoxml.logWrite(text2, strLog, rxmlstr, id, proctype);
            string cUserName = u8login.cUserName;
            string text3 = DateTime.Now.Month.ToString();
            if (text3.Length == 1)
            {
                text3 = "0" + text3;
            }
            string text4 = DateTime.Now.Day.ToString();
            if (text4.Length == 1)
            {
                text4 = "0" + text4;
            }
            string text5 = DateTime.Now.Year + "-" + text3 + "-" + text4;
            string text6 = null;
            string text7 = "0";
            switch (proctype)
            {
                case "1":
                    text6 = "add";
                    text7 = "0";
                    break;
                case "2":
                    text6 = "edit";
                    text7 = "0";
                    break;
                case "3":
                    text6 = "delete";
                    text7 = "1";
                    break;
                case "4":
                    text6 = "empty";
                    text7 = "1";
                    break;
            }
            string cmdText = "insert into log(importtime,type,name,filename,succeeded,failed,username,token,ImportType,DeleteTag) values('" + text5 + "','" + id + "','" + name + "','" + logpath + text + "'," + scount + "," + (count - scount) + ",'" + cUserName + "','" + token + "','" + text6 + "'," + text7 + ")";
            OleDbCommand oleDbCommand = new OleDbCommand(cmdText, oleDbConnection);
            try
            {
                oleDbCommand.ExecuteNonQuery();
            }
            catch (OleDbException ex)
            {
                MessageBox.Show("日志数据库操作错误:" + ex.Message);
            }
            oleDbConnection.Close();
        }

        private void InitialProgressBar(int IntInitial, string DocName)
        {
            string strCaption = "";
            switch (m_proctype)
            {
                case "1":
                    strCaption = "正在导入" + DocName + ",请稍候..........";
                    break;
                case "2":
                    strCaption = "正在导入" + DocName + ",请稍候..........";
                    break;
                case "3":
                    strCaption = "正在删除" + DocName + "中的数据,请稍候..........";
                    break;
                case "4":
                    strCaption = "正在清空" + DocName + "中的数据,请稍候..........";
                    break;
            }
            fpBar.InitSingleDoc(IntInitial, NowDocNum, strCaption);
        }

        private void SetProgressBar(int IntValue)
        {
            fpBar.ExSetValue(IntValue, 0.5);
        }

        private void SetImportProgressBar(string StrXml)
        {
            if (StrXml != null)
            {
                int intStep = 0;
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(StrXml);
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/ufinterface/item");
                if (xmlNodeList != null)
                {
                    intStep = xmlNodeList.Count;
                }
                fpBar.StepForward(intStep, 0.5);
            }
        }

        private string[,] AdjustReturnStr(string[] xmldata, string[] rxmlstr)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlDocument xmlDocument2 = new XmlDocument();
            int logArrayLength = GetLogArrayLength(xmldata);
            string[,] array = new string[logArrayLength + 1, 1];
            array[0, 0] = "导入失败原因";
            if (rxmlstr == null || rxmlstr.Length == 0)
            {
                return array;
            }
            int num = 0;
            for (int i = 0; i < xmldata.Length; i++)
            {
                if (rxmlstr[i] == null)
                {
                    continue;
                }
                xmlDocument.LoadXml(rxmlstr[i]);
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/ufinterface/item");
                xmlDocument2.LoadXml(xmldata[i]);
                XmlNode xmlNode = xmlDocument2.SelectSingleNode("/ufinterface");
                string innerText = xmlNode.Attributes["roottag"].InnerText;
                XmlNodeList xmlNodeList2 = xmlDocument2.SelectNodes("/ufinterface/" + innerText);
                int num2 = 0;
                foreach (XmlElement item in xmlNodeList2)
                {
                    int subItemCount = GetSubItemCount(item);
                    if (subItemCount > 1)
                    {
                        if (xmlNodeList != null)
                        {
                            XmlNode xmlNode2 = xmlNodeList[num2];
                            for (int j = 0; j < subItemCount; j++)
                            {
                                if (xmlNode2 != null)
                                {
                                    array[num + 1, 0] = xmlNode2.Attributes["dsc"].InnerText;
                                }
                                else
                                {
                                    array[num + 1, 0] = "导入情况不明";
                                }
                                num++;
                            }
                        }
                    }
                    else if (xmlNodeList != null)
                    {
                        XmlNode xmlNode2 = xmlNodeList[num2];
                        if (xmlNode2 != null)
                        {
                            array[num + 1, 0] = xmlNode2.Attributes["dsc"].InnerText;
                        }
                        else
                        {
                            array[num + 1, 0] = "导入情况不明";
                        }
                        num++;
                    }
                    num2++;
                }
            }
            return array;
        }

        private int GetLogArrayLength(string[] xmldata)
        {
            if (xmldata == null || xmldata.Length == 0)
            {
                return 0;
            }
            XmlDocument xmlDocument = new XmlDocument();
            int num = 0;
            for (int i = 0; i < xmldata.Length; i++)
            {
                xmlDocument.LoadXml(xmldata[i]);
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/ufinterface");
                string innerText = xmlNode.Attributes["roottag"].InnerText;
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/ufinterface/" + innerText);
                foreach (XmlElement item in xmlNodeList)
                {
                    num += GetSubItemCount(item);
                }
            }
            return num;
        }

        private int GetSubItemCount(XmlElement element)
        {
            XmlNodeList xmlNodeList = element.SelectNodes("body");
            XmlNodeList xmlNodeList2 = element.SelectNodes("body/entry");
            XmlNodeList xmlNodeList3 = element.SelectNodes("Body");
            XmlNodeList xmlNodeList4 = element.SelectNodes("Body/Entry");
            XmlNodeList xmlNodeList5 = element.SelectNodes("body/Entry");
            XmlNodeList xmlNodeList6 = element.SelectNodes("Body/entry");
            XmlNodeList xmlNodeList7 = element.SelectNodes("OperationRes");
            int num = 0;
            num = Math.Max(Math.Max(xmlNodeList.Count, xmlNodeList2.Count), Math.Max(xmlNodeList3.Count, xmlNodeList4.Count));
            num = Math.Max(xmlNodeList5.Count, num);
            num = Math.Max(xmlNodeList6.Count, num);
            num = Math.Max(xmlNodeList7.Count, num);
            if (num == 0)
            {
                num = 1;
            }
            return num;
        }

        private void GetSucceedImportCount(string[] strReturnXml, ref int count, ref int scount)
        {
            XmlDocument xmlDocument = new XmlDocument();
            count = 0;
            scount = 0;
            if (strReturnXml == null || strReturnXml.Length == 0)
            {
                return;
            }
            for (int i = 0; i < strReturnXml.Length; i++)
            {
                if (strReturnXml[i] != null)
                {
                    xmlDocument.LoadXml(strReturnXml[i]);
                    XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/ufinterface/item");
                    if (xmlNodeList != null)
                    {
                        count += xmlNodeList.Count;
                    }
                    XmlNodeList xmlNodeList2 = xmlDocument.SelectNodes("/ufinterface/item[@succeed=0]");
                    if (xmlNodeList2 != null)
                    {
                        scount += xmlNodeList2.Count;
                    }
                }
            }
        }

        private bool XmlIsValid(string[] xml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            for (int i = 0; i < xml.Length; i++)
            {
                try
                {
                    xmlDocument.LoadXml(xml[i]);
                }
                catch (XmlException)
                {
                    MessageBox.Show("IDataImport得到的xml数据格式错误");
                    return false;
                }
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/ufinterface");
                if (xmlNode == null)
                {
                    MessageBox.Show("IDataImport得到的xml数据缺少ufinterface节点");
                    return false;
                }
                string innerText = xmlNode.Attributes["roottag"].InnerText;
                XmlNodeList xmlNodeList = xmlDocument.SelectNodes("/ufinterface/" + innerText);
                if (xmlNodeList == null)
                {
                    MessageBox.Show("IDataImport得到的xml数据中，ufinterface节点的roottag属性值为" + innerText + "，系统无法找到一些" + innerText + "子节点");
                    return false;
                }
            }
            return true;
        }

        private string[] ParseXmlOnebyOne(string id, string[] oldXml)
        {
            XmlDocument xmlDocument = new XmlDocument();
            int num = 0;
            for (int i = 0; i < oldXml.Length; i++)
            {
                xmlDocument.LoadXml(oldXml[i]);
                XmlNode xmlNode = xmlDocument.SelectSingleNode("/ufinterface");
                string innerText = xmlNode.Attributes["roottag"].InnerText;
                XmlNodeList xmlNodeList = ((!(innerText == "ForecastVSes")) ? xmlDocument.SelectNodes("/ufinterface/" + innerText) : xmlDocument.SelectNodes("/ufinterface/" + innerText + "/ForecastVS"));
                num += xmlNodeList.Count;
            }
            Hashtable hashtable = new Hashtable();
            XmlDocument xmlDocument2 = new XmlDocument();
            string filename = Context.QIPath + "\\Xml\\ImportConfig.xml";
            xmlDocument2.Load(filename);
            if (xmlDocument2 != null)
            {
                XmlNode xmlNode2 = xmlDocument2.SelectSingleNode("/U8QuickImport/ImportStrategy");
                if (xmlNode2 != null)
                {
                    XmlNodeList childNodes = xmlNode2.ChildNodes;
                    if (childNodes != null)
                    {
                        foreach (XmlNode item in childNodes)
                        {
                            if (item == null)
                            {
                                continue;
                            }
                            XmlNode xmlNode4 = item.Attributes["batchImport"];
                            if (xmlNode4 != null)
                            {
                                string text = xmlNode4.Value.Trim();
                                if (text == "true")
                                {
                                    hashtable.Add(item.Name, item.Name);
                                }
                            }
                        }
                    }
                }
            }
            string[] array;
            if (!hashtable.ContainsKey(id))
            {
                array = new string[num];
                if (num > 0)
                {
                    int num2 = 0;
                    for (int j = 0; j < oldXml.Length; j++)
                    {
                        xmlDocument.LoadXml(oldXml[j]);
                        XmlNode xmlNode5 = xmlDocument.CloneNode(true);
                        XmlNode xmlNode6 = xmlNode5.SelectSingleNode("/ufinterface");
                        string innerText = xmlNode6.Attributes["roottag"].InnerText;
                        XmlNodeList xmlNodeList2;
                        if (innerText == "ForecastVSes")
                        {
                            xmlNode6 = xmlNode5.SelectSingleNode("/ufinterface/" + innerText);
                            xmlNodeList2 = xmlNode5.SelectNodes("/ufinterface/" + innerText + "/ForecastVS");
                        }
                        else
                        {
                            xmlNodeList2 = xmlNode5.SelectNodes("/ufinterface/" + innerText);
                        }
                        for (int k = 1; k < xmlNodeList2.Count; k++)
                        {
                            xmlNode6.RemoveChild(xmlNodeList2.Item(k));
                        }
                        array[num2] = xmlNode5.InnerXml;
                        num2++;
                        for (int l = 1; l < xmlNodeList2.Count; l++)
                        {
                            xmlNode6.ReplaceChild(xmlNodeList2.Item(l), xmlNodeList2.Item(l - 1));
                            array[num2] = xmlNode5.InnerXml;
                            num2++;
                        }
                    }
                }
            }
            else
            {
                array = new string[oldXml.Length];
                for (int m = 0; m < array.Length; m++)
                {
                    array[m] = oldXml[m];
                }
            }
            return array;
        }
    }
}